//
//  TCLYSubmitOrderViewController.m
//  YuErmuYing
//
//  Created by LYang on 16/9/3.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "TCLYSubmitOrderViewController.h"
#import "TCLYHomeModel.h"
#import "Macros.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "TCLYSubmitAddressViewController.h"
#import "TCLYOrderSucceedViewController.h"
#import "TCLYRegisterView.h"
#import "TCLYUser.h"

@interface TCLYSubmitOrderViewController ()
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewLayout;
//收货人的label
@property (weak, nonatomic) IBOutlet UILabel *manNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *addressImageView;
//联系电话
@property (weak, nonatomic) IBOutlet UILabel *telLabel;
//地址
@property (weak, nonatomic) IBOutlet UILabel *adressLabel;
//选择地址的按钮
@property (weak, nonatomic) IBOutlet UIButton *adressBtn;
//商品图片
@property (weak, nonatomic) IBOutlet UIImageView *goodsImageView;
//物品的名字
@property (weak, nonatomic) IBOutlet UILabel *goodsNameLabel;
//规格型号
@property (weak, nonatomic) IBOutlet UILabel *goodsSizeLabel;
//单价
@property (weak, nonatomic) IBOutlet UILabel *goodsPriceLabel;
//数量减少
@property (weak, nonatomic) IBOutlet UIButton *jianBtn;
//数量增加
@property (weak, nonatomic) IBOutlet UIButton *increaseBtn;
//物品数量
@property (weak, nonatomic) IBOutlet UILabel *goodsNumLabel;
//邮费
@property (weak, nonatomic) IBOutlet UILabel *postageLabel;
//填写留言的textField
@property (weak, nonatomic) IBOutlet UITextField *messageTextField;
//商品的总价
@property (weak, nonatomic) IBOutlet UILabel *goodsSumPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *goodsSumNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *sumPriceeLabel;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (nonatomic, strong)TCLYHomeModel * homeModel;
@property (nonatomic, strong)TCLYRegisterView * registerView;
@property (nonatomic, assign)double sumPrice;
@property (nonatomic, assign)int sumNum;
@property (nonatomic, strong) TCLYUser * user;
@end

@implementation TCLYSubmitOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer * textFeildTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:textFeildTap];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exchangeIntegralGoods) name:@"exchangeIntegralGoods" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSucceed:) name:@"updateSucceed" object:nil];
    
    self.navigationController.navigationBarHidden = NO;
    self.bgView.backgroundColor = bgColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadIntegralOrder) name:@"loadIntegralOrder" object:nil];
    self.homeModel = [[TCLYHomeModel alloc] init];
    self.registerView = [[TCLYRegisterView alloc] init];
    self.user = [[TCLYUser alloc] init];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"user_id", self.parameterDic[@"id"], @"goods_id", nil];
    [self.homeModel loadSubmitOrderParameter:dic];
    [self createTitleView];
}
-(void)loadIntegralOrder{
    [self createView];
    NSURL * url = [NSURL URLWithString:self.homeModel.integralOrderDic[@"goods_pic"]];
    [self.goodsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"LYJia2"]];
    self.goodsNameLabel.text = [NSString stringWithFormat:@"%@%@",self.homeModel.integralOrderDic[@"brand"],self.homeModel.integralOrderDic[@"goods_name"]];
    self.goodsSizeLabel.text = self.homeModel.integralOrderDic[@"standard"];
    self.goodsPriceLabel.text = [NSString stringWithFormat:@"∫%@",self.homeModel.integralOrderDic[@"integral_val"]];
    self.goodsNumLabel.text = @"1";
    self.postageLabel.text = @"0 元";
    
    self.goodsSumNumLabel.text = [NSString stringWithFormat:@"共1件商品"];
    self.goodsSumPriceLabel.text = [NSString stringWithFormat:@"∫%@",self.homeModel.integralOrderDic[@"integral_val"]];
    
    self.sumPriceeLabel.text = [NSString stringWithFormat:@"∫%@",self.homeModel.integralOrderDic[@"integral_val"]];
    NSString * str = self.homeModel.integralOrderDic[@"integral_val"];
    self.sumPrice = str.doubleValue;
    self.sumNum = 1;
    
    NSLog(@"%@",self.homeModel.integralAdderssDic);
    if ([self.homeModel.integralAdderssDic isEqual:@"0"]) {
        [self.registerView Prompt:@"您要马上去设置收货地址吗" Controller:self];
        self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            TCLYSubmitAddressViewController * submitAddressViewCtr = [[TCLYSubmitAddressViewController alloc] init];
            [self.navigationController pushViewController:submitAddressViewCtr animated:YES];
            return ;
        }];
        self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return;
        }];
        [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
        [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
        return;
    }
    self.manNameLabel.text = [NSString stringWithFormat:@"收货人: %@",self.homeModel.integralAdderssDic[@"address_consignee"]];
    self.telLabel.text = self.homeModel.integralAdderssDic[@"address_consignee_phone"];
    self.adressLabel.text = [NSString stringWithFormat:@"%@%@",self.homeModel.integralAdderssDic[@"address_add"],self.homeModel.integralAdderssDic[@"address_detail"]];
    
}
-(void)createView{
    self.addressImageView.image = [UIImage imageNamed:@"integralPin"];
    [self.adressBtn setImage:[UIImage imageNamed:@"right"] forState:UIControlStateNormal];
    [self.increaseBtn setImage:[UIImage imageNamed:@"integralPlus"] forState:UIControlStateNormal];
    [self.jianBtn setImage:[UIImage imageNamed:@"integralMin"] forState:UIControlStateNormal];
}
-(void) updateSucceed:(NSNotification *)notification{
    NSLog(@"收到通知");
    self.upDateDic = notification.userInfo;
    self.manNameLabel.text = notification.userInfo[@"address_consignee"];
    self.telLabel.text = notification.userInfo[@"address_consignee_phone"];
    self.adressLabel.text = [NSString stringWithFormat:@"%@%@",notification.userInfo[@"address_add"],notification.userInfo[@"address_detail"]];
}

-(void)createTitleView{
    self.navigationController.navigationBar.barStyle = UIBarMetricsCompactPrompt;
    self.navigationController.navigationBar.backgroundColor = statusColor;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, screenWidth, 20)];
    view.backgroundColor = navColor;
    [self.navigationController.navigationBar addSubview:view];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"确认订单";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.frame = CGRectMake(0, 0, 50, 20);
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = titleLabel;
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(12, 22, 20, 20);
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    leftBtn.tag = 91;
    [leftBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
}
-(void)statusBtnAction:(id)sender{
    switch (((UIButton *)sender).tag) {
        case 91:{
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.navigationBarHidden = YES;
            self.tabBarController.tabBar.hidden = YES;
        }
            break;
        case 92:{
            
        }
            break;
    }
}

-(IBAction)addressBtnAction:(id)sender{
    TCLYSubmitAddressViewController * submitAddressViewCtr = [[TCLYSubmitAddressViewController alloc] init];
    [self.navigationController pushViewController:submitAddressViewCtr animated:YES];
}
-(IBAction)numBtnAction:(id)sender{
    static int num = 1;
    if ([(UIButton *)sender isEqual:self.increaseBtn]) {
        num++;
    }else if ([(UIButton *)sender isEqual:self.jianBtn]){
        if (num > 1) {
            num--;
        }else{
            num = 1;
        }
    }
    self.goodsNumLabel.text = [NSString stringWithFormat:@"%d",num];
    self.goodsSumNumLabel.text = [NSString stringWithFormat:@"共%d件商品",num];
    self.sumNum = num;
    NSString * str = self.homeModel.integralOrderDic[@"integral_val"];
    self.sumPrice = str.doubleValue;
    self.goodsSumPriceLabel.text = [NSString stringWithFormat:@"∫%.2f",self.sumPrice*num];
    self.sumPriceeLabel.text = [NSString stringWithFormat:@"∫%.2f",self.sumPrice*num];
}

-(IBAction)submitBtnAction:(id)sender{
    NSLog(@"%d",self.sumNum);
    if (self.upDateDic == nil) {
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys: self.parameterDic[@"id"], @"goods_id", self.homeModel.integralAdderssDic[@"address_id"], @"address_id",self.user.userId,@"user_id", [NSString stringWithFormat:@"%d",self.sumNum],@"goods_num", self.messageTextField.text,@"buyer_message", self.goodsSumPriceLabel.text,@"total_val", nil];
        [self.homeModel exchangeIntegralGoodsParameter:dic];
    }else{
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys: self.parameterDic[@"id"], @"goods_id", self.user.userId, @"user_id",self.upDateDic[@"address_id"],@"address_id", [NSString stringWithFormat:@"%d",self.sumNum],@"goods_num", self.messageTextField.text,@"buyer_message", self.goodsSumPriceLabel.text,@"total_val", nil];
        [self.homeModel exchangeIntegralGoodsParameter:dic];
    }
    NSLog(@"s%@",self.upDateDic);
    NSLog(@"GG%f",self.sumPrice);
}
-(void)exchangeIntegralGoods{
    
    NSLog(@"%@",self.homeModel.succeedStr);
    if ([self.homeModel.succeedStr isEqual:@"积分不足"]) {
        [self.registerView Prompt:@"您的积分不足哦" Controller:self];
        self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return ;
        }];
        self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return;
        }];
        [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
        [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
        
    }else if ([self.homeModel.succeedStr isEqual:@"该商品库存不足"]){
        [self.registerView Prompt:@"商品库存不足" Controller:self];
        self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return ;
        }];
        self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return;
        }];
        [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
        [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
    }else if ([self.homeModel.succeedStr isEqual:@"订单没有成功"]){
        [self.registerView Prompt:@"没有兑换成功请稍后再试" Controller:self];
        self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return ;
        }];
        self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            return;
        }];
        [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
        [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
    }else{
        NSLog(@"兑换成功");
        TCLYOrderSucceedViewController * orderSuccedViewCtr = [[TCLYOrderSucceedViewController alloc] init];
        orderSuccedViewCtr.parameterStr = self.homeModel.succeedStr;
        NSLog(@"%@",orderSuccedViewCtr.parameterStr);
        self.navigationController.navigationBarHidden = YES;
        [self.navigationController pushViewController:orderSuccedViewCtr animated:YES];        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"exchange" object:self];
    }
}
//隐藏键盘的方法
-(void)dismissKeyboard{
    [self.messageTextField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
